package com.liu.qqRobot.event.service.impl;

import com.liu.common.utils.QQClientUtils;
import com.liu.qqRobot.climbingTower.handler.ClimbingTowerMyBackpackHandler;
import com.liu.qqRobot.climbingTower.handler.ClimbingTowerMyInfoHandler;
import com.liu.qqRobot.climbingTower.handler.ClimbingTowerStartHandler;
import com.liu.qqRobot.climbingTower.handler.ClimbingTowerUseArticleHandler;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.event.enums.EventPostTypeEnum;
import com.liu.qqRobot.event.enums.MessageSubTypeEnum;
import com.liu.qqRobot.event.enums.MessageTypeEnum;
import com.liu.qqRobot.event.enums.RequestTypeEnum;
import com.liu.qqRobot.event.service.EventService;
import com.liu.qqRobot.myself.handler.BotMenuHandler;
import com.liu.qqRobot.myself.handler.CircuitHandler;
import com.liu.qqRobot.myself.handler.JmHandler;
import com.liu.qqRobot.myself.handler.RaHandler;
import com.liu.qqRobot.poke.handler.*;
import com.liu.qqRobot.q.handler.LoginHandler;
import com.liu.qqRobot.q.handler.MyRequestHandler;
import com.liu.qqRobot.wia.handler.*;
import com.liu.qqRobot.wiki.handler.WikiHandler;
import com.liu.qqRobot.wm.handler.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Slf4j
@Service
public class EventServiceImpl implements EventService {

    @Resource
    private WikiHandler wikiHandler;

    @Resource
    private BotMenuHandler botMenuHandler;

    @Resource
    private WmHandler wmHandler;

    @Resource
    private WmlHandler wmlHandler;

    @Resource
    private WmsHandler wmsHandler;

    @Resource
    private WmrHandler wmrHandler;

    @Resource
    private WmrlHandler wmrlHandler;

    @Resource
    private com.liu.qqRobot.wm.handler.wmrldHandler wmrldHandler;

    @Resource
    private RaHandler raHandler;

    @Resource
    private CatchPokeHandler catchPokeHandler;

    @Resource
    private ComeOutPokeHandler comeOutPokeHandler;

    @Resource
    private MyRequestHandler myRequestHandler;

    @Resource
    private MyPokeHandler myPokeHandler;

    @Resource
    private UseSkillHandler useSkillHandler;

    @Resource
    private ReleasePokeHandler releasePokeHandler;

    @Resource
    private ClimbingTowerStartHandler climbingTowerStartHandler;

    @Resource
    private SeekPokeHandler seekPokeHandler;

    @Resource
    private LoginHandler loginHandler;

    @Resource
    private EventsHandler eventsHandler;

    @Resource
    private AlertsHandler alertsHandler;

    @Resource
    private SortieHandler sortieHandler;

    @Resource
    private OstronsHandler ostronsHandler;

    @Resource
    private SolarisHandler solarisHandler;

    @Resource
    private EntratiSyndicateHandler entratiSyndicateHandler;

    @Resource
    private FissuresHandler fissuresHandler;

    @Resource
    private CircuitHandler circuitHandler;

    @Resource
    private VoidTraderHandler voidTraderHandler;

    @Resource
    private DailyDealsHandler dailyDealsHandler;

    @Resource
    private PlainTimeHandler plainTimeHandler;

    @Resource
    private ConstructionProgressHandler constructionProgressHandler;

    @Resource
    private NightwaveHandler nightwaveHandler;

    @Resource
    private ArchonHuntHandler archonHuntHandler;

    @Resource
    private InvasionsHandler invasionsHandler;

    @Resource
    private SteelPathHandler steelPathHandler;

    @Resource
    private ClimbingTowerMyInfoHandler climbingTowerMyInfoHandler;

    @Resource
    private ClimbingTowerMyBackpackHandler climbingTowerMyBackpackHandler;

    @Resource
    private ClimbingTowerUseArticleHandler climbingTowerUseArticleHandler;

    @Resource
    private JmHandler jmHandler;

    @Override
    public void handleEvent(EventReportingDTO eventReportingDTO) {
        String postType = eventReportingDTO.getPostType();
        if (EventPostTypeEnum.MESSAGE.getType().equals(postType)) {
            handleMessageEvent(eventReportingDTO);
        } else if (EventPostTypeEnum.REQUEST.getType().equals(postType)) {
            handleRequestEvent(eventReportingDTO);
        }
    }

    /**
     * 处理消息事件
     */
    private void handleMessageEvent(EventReportingDTO eventReportingDTO) {
        String messageType = eventReportingDTO.getMessageType();
        String subType = eventReportingDTO.getSubType();

        // 检查消息类型和子类型是否合法
        if (!isValidMessageType(messageType) || !isValidSubType(subType)) {
            return;
        }

        List<EventReportingDTO.Message> messages = eventReportingDTO.getMessage();
        if (messages.isEmpty()) {
            return;
        }

        Boolean isGroup = QQClientUtils.checkIsGroup(messageType, subType);

        if (messages.size() == 1) {
            handleSingleMessage(messages.get(0), eventReportingDTO, isGroup);
        } else {
            handleMultipleMessages(messages, eventReportingDTO, isGroup);
        }
    }

    /**
     * 处理单条消息
     */
    private void handleSingleMessage(EventReportingDTO.Message message, EventReportingDTO eventReportingDTO, Boolean isGroup) {
        if (!"text".equals(message.getType())) {
            return;
        }
        String text = message.getData().getText();
        Long groupId = eventReportingDTO.getGroupId();
        Long userId = eventReportingDTO.getUserId();
        // 使用策略模式处理不同的命令
        Map<String, Consumer<String>> commandHandlers = new HashMap<>();
        // WARFRAME
        commandHandlers.put("wm ", cmd -> wmHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wml ", cmd -> wmlHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wms ", cmd -> wmsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wmr ", cmd -> wmrHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wmrl ", cmd -> wmrlHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wmrld ", cmd -> wmrldHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("ra ", cmd -> raHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("wiki ", cmd -> wikiHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("活动", cmd -> eventsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("警报", cmd -> alertsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("突击", cmd -> sortieHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("地球赏金", cmd -> ostronsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("金星赏金", cmd -> solarisHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("火卫二赏金", cmd -> entratiSyndicateHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("裂隙", cmd -> fissuresHandler.handler(message.getData(), groupId, userId, isGroup, 1));
        commandHandlers.put("钢铁裂隙", cmd -> fissuresHandler.handler(message.getData(), groupId, userId, isGroup, 2));
        commandHandlers.put("钢铁裂缝", cmd -> fissuresHandler.handler(message.getData(), groupId, userId, isGroup, 2));
        commandHandlers.put("九重天", cmd -> fissuresHandler.handler(message.getData(), groupId, userId, isGroup, 3));
        commandHandlers.put("本周灵化", cmd -> circuitHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("奸商", cmd -> voidTraderHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("每日特惠", cmd -> dailyDealsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("平原", cmd -> plainTimeHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("舰队进度", cmd -> constructionProgressHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("电波", cmd -> nightwaveHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("执行官", cmd -> archonHuntHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("入侵", cmd -> invasionsHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("钢铁之路", cmd -> steelPathHandler.handler(message.getData(), groupId, userId, isGroup));
        // poke
        commandHandlers.put("捕捉宝可梦", cmd -> catchPokeHandler.handler(message.getData(), groupId, userId, isGroup, 1));
        commandHandlers.put("我的宝可梦", cmd -> myPokeHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("放生 ", cmd -> releasePokeHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("寻找233", cmd -> seekPokeHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("捕捉 ", cmd -> catchPokeHandler.handler(message.getData(), groupId, userId, isGroup, 2));
        // 爬塔
        commandHandlers.put("爬塔", cmd -> climbingTowerStartHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("爬塔 我的信息", cmd -> climbingTowerMyInfoHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("爬塔 使用 ", cmd -> climbingTowerUseArticleHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("爬塔 我的背包", cmd -> climbingTowerMyBackpackHandler.handler(message.getData(), groupId, userId, isGroup));
        // 基础
        commandHandlers.put("菜单 ", cmd -> botMenuHandler.handler(message.getData(), groupId, userId, isGroup));
        commandHandlers.put("我的调用次数", cmd -> myRequestHandler.handler(message.getData(), groupId, userId, isGroup));
        // 网页
        commandHandlers.put("确认登录", cmd -> loginHandler.handler(message.getData(), groupId, userId, isGroup));
        // 其他
        commandHandlers.put("jm ", cmd -> jmHandler.handler(message.getData(), groupId));
        // 查找匹配的命令并执行
        commandHandlers.entrySet().stream()
                .filter(entry -> {
                    if (entry.getKey().equals(text)) {
                        return true;
                    } else {
                        return text.startsWith(entry.getKey()) && entry.getKey().contains(" ");
                    }
                })
                .findFirst()
                .ifPresent(entry -> entry.getValue().accept(text));
    }

    /**
     * 处理多条消息
     */
    private void handleMultipleMessages(List<EventReportingDTO.Message> messages, EventReportingDTO eventReportingDTO, Boolean isGroup) {
        List<String> msgTypeList = messages.stream()
                .map(EventReportingDTO.Message::getType)
                .toList();

        if (msgTypeList.contains("image")) {
            List<String> msgList = messages.stream()
                    .map(m -> m.getData().getText() != null ? m.getData().getText() : m.getData().getUrl())
                    .toList();

            if (judgeHaveRa(msgList) && msgList.size() == 2) {
                raHandler.handler(msgList, eventReportingDTO.getGroupId(), eventReportingDTO.getUserId(), isGroup);
            }
        }
    }

    /**
     * 判断是否ra指令
     * @param msgList msgList
     * @return Boolean
     */
    private Boolean judgeHaveRa(List<String> msgList) {
        for (String msg : msgList) {
            if (msg.startsWith("ra")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理请求事件
     */
    private void handleRequestEvent(EventReportingDTO eventReportingDTO) {
        String requestType = eventReportingDTO.getRequestType();
        String subType = eventReportingDTO.getSubType();

        if (RequestTypeEnum.FRIEND.getType().equals(requestType)) {
            QQClientUtils.agreeWithAddFriend(eventReportingDTO.getFlag());
        } else if (RequestTypeEnum.GROUP.getType().equals(requestType)) {
            if ("invite".equals(subType) || "add".equals(subType)) {
                QQClientUtils.agreeWithAddGroup(eventReportingDTO.getFlag(), subType);
            }
        }
    }

    /**
     * 检查消息类型是否合法
     */
    private boolean isValidMessageType(String messageType) {
        return MessageTypeEnum.GROUP.getType().equals(messageType) || MessageTypeEnum.PRIVATE.getType().equals(messageType);
    }

    /**
     * 检查子类型是否合法
     */
    private boolean isValidSubType(String subType) {
        return MessageSubTypeEnum.NORMAL.getType().equals(subType) ||
                MessageSubTypeEnum.FRIEND.getType().equals(subType) ||
                MessageSubTypeEnum.GROUP.getType().equals(subType);
    }
}
